import { Component, instantiate, Node, Prefab, UITransform, _decorator } from 'cc';
import { IRect } from '../../game/lib/kgame/util/Defined';
const { ccclass, property } = _decorator;

@ccclass('Background')
export class Background extends Component {

    @property(Prefab)
    prefab: Prefab
    rect: IRect;
    oneSize: number;

    start() {
        this.oneSize = (this.prefab.data as Node).getComponent(UITransform).width;
    }

    /**
     * 更新背景
     * @param rect 世界大小
     */
    updateBg(rect: IRect) {
        this.node.removeAllChildren();

        this.rect = rect;

        const x = rect.width / this.oneSize >> 0;
        const y = rect.height / this.oneSize >> 0;
        for (let i = 0; i < y; ++i) {
            for (let j = 0; j < x; ++j) {
                this.createBg(i, j);
            }
        }
        const leftWidth = rect.width % this.oneSize;
        const leftHeight = rect.height % this.oneSize;
        if (leftWidth > 0) {
            for (let i = 0; i < y; ++i) {
                this.createBg(x, i, leftWidth, this.oneSize);
            }
        }
        if (leftHeight > 0) {
            for (let i = 0; i < x; ++i) {
                this.createBg(i, y, this.oneSize, leftHeight);
            }
        }
        if (leftWidth > 0 && leftHeight > 0) {
            this.createBg(x, y, leftWidth, leftHeight);
        }
    }

    private createBg(x: number, y: number, width?: number, height?: number) {
        const bg = instantiate(this.prefab);
        bg.setPosition(this.rect.x + x * this.oneSize, this.rect.y + y * this.oneSize);
        if (width !== undefined) {
            bg.getComponent(UITransform).setContentSize(width, height);
        }
        this.node.addChild(bg);
    }
}


